package antlr.cal;

import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;

public class Main {
    public static void main(String[] args) {
        String input = "3+2*5";
        CalLexer lexer = new CalLexer(CharStreams.fromString(input));
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        CalParser parser = new CalParser(tokens);
        ParseTree tree = parser.expr();
        System.out.println("Parse tree: " + tree.toStringTree(parser));

        EvalVisitor eval = new EvalVisitor();
        int result = eval.visit(tree);
        System.out.println("Result: " + result);
    }
}

class EvalVisitor extends CalBaseVisitor<Integer> {
    @Override
    public Integer visitExpr(CalParser.ExprContext ctx) {
        if (ctx.INT() != null) {
            return Integer.parseInt(ctx.INT().getText());
        }
        int left = visit(ctx.expr(0));
        if (ctx.op == null) {  // check if operator exists
            return left;
        }
        int right = visit(ctx.expr(1));
        switch (ctx.op.getType()) {
            case CalParser.MUL:
                return left * right;
            case CalParser.DIV:
                return left / right;
            case CalParser.ADD:
                return left + right;
            case CalParser.SUB:
                return left - right;
            default:
                throw new RuntimeException("Unknown operator: " + ctx.op.getText());
        }
    }
}
